﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using System.Configuration;
using Tracker.Data.DataTransfer;
using Tracker.Views;
using Microsoft.Reporting.WinForms;


namespace Tracker
{
    public partial class Tracker : Form,ITrackerView
    {
        #region Private fields
        #endregion


        public Tracker()
        {
            InitializeComponent();
        }
       
        #region Event handling
        private void Tracker_Load(object sender, EventArgs e)
        {
            InitializeTaskView(sender, e);
        }
        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();

        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            InitializeDetailSearchView(sender,e);
        }

        private void btnRefreshSummary_Click(object sender, EventArgs e)
        {
            InitializeSummarySearchView(sender,e);
        }

        private void dataGridViewTaskList_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            Task t = dataGridViewTaskList.SelectedRows[0].DataBoundItem as Task;
            InitializeLogView(sender,t);
        }

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            if (this.Visible == true)
            {
                DeactivateApp();

            }
            else
            {

                ActivateApp();

            }

        }

        private void Files_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (dataGridViewTaskList.SelectedRows.Count > 0)
            {
                string ItemName = (dataGridViewTaskList.SelectedRows[0].DataBoundItem as dynamic).Description;
                FilesLinkClicked(sender,ItemName);
            }

        }

        private void btnTaskRefresh_Click(object sender, EventArgs e)
        {
            InitializeTaskView(sender, e);

        }

        private void dataGridViewTaskList_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            var c = dataGridViewTaskList[e.ColumnIndex, e.RowIndex];
            if (c != null)
            {
                var t = c.OwningRow.DataBoundItem as Task;
                if (t != null)
                {
                    UpdateTask(sender,t);
                    dataGridViewTaskList.Refresh();

                }

            }
        }

        private void dataGridViewTaskDetail_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            var c = dataGridViewTaskDetail[e.ColumnIndex, e.RowIndex];

            if (c != null)
            {
                var l = c.OwningRow.DataBoundItem as Log;
                if (l != null && l.TaskId > 0)
                {
                    UpdateLog(sender, l);
                    dataGridViewTaskDetail.Refresh();
                }

            }
        }
        
        private void dataGridViewTaskList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0 )
                if(dataGridViewTaskList.Columns["Delete"].Index == e.ColumnIndex)
                {
                    var task = dataGridViewTaskList.Rows[e.RowIndex].DataBoundItem as Task;
                    if (task != null)
                    {
                        DeleteTask(sender,task);

                    }
                }
        }

        private void dataGridViewTaskDetail_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0 || e.ColumnIndex < 0 || dataGridViewTaskDetail.Columns[e.ColumnIndex].Name != "Delete") return;


            var log = dataGridViewTaskDetail.Rows[e.RowIndex].DataBoundItem as Log;
            if (log != null)
            {
               DeleteLog(sender,log);
               InitializeLogView(sender,new Task() { ID = log.Task_logTask.ID, Description = log.Task_logTask.Description });
            }
        }

        private void buttonSubmitRpt_Click(object sender, EventArgs e)
        {
            InitializeReport(sender,  e);
        }
        
        private void dataGridViewTaskList_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            Task t = dataGridViewTaskList.Rows[e.RowIndex].DataBoundItem as Task;
            InitializeLogView(sender,t);
        }
       
        #endregion

        #region notify icon handling
       
        private void ActivateApp()
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Show();
                this.WindowState = FormWindowState.Normal;
            }
            this.Visible = true;
            this.Activate();
            this.Focus();
        }
        private void DeactivateApp()
        {
            if (this == null)
            {
                return;
            }
            this.Visible = false;
            this.Hide();
        }

        private void Form1_Move(object sender, EventArgs e)
        {
            if (this == null)
            {
                return;
            }
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide();
                this.notifyIcon1.ShowBalloonTip(500, "Tracker", "This app moved to tray", ToolTipIcon.Info);
            }
            else
            {
                this.Show();
            }
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void viewDetailsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ActivateApp();
        }

        private void createTaskToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ActivateApp();
        }

        private void updateTaskToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ActivateApp();
        }
        private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowOptionForm(this, e);
           
        }

        #endregion

        #region Trackerview Interface Implementation

        public event EventHandler ShowOptionForm;
        public event EventHandler<Task> InitializeLogView;
        public event EventHandler<Log> DeleteLog;
        public event EventHandler InitializeReport;
        public event EventHandler<Task> DeleteTask;
        public event EventHandler<Log> UpdateLog;
        public event EventHandler<Task> UpdateTask;
        public event EventHandler InitializeTaskView;
        public event EventHandler InitializeSummarySearchView;
        public event EventHandler InitializeDetailSearchView;
        public event EventHandler<string> FilesLinkClicked;
        
        

        public Task CurrentTask
        {
            get
            {
               return dataGridViewTaskList.CurrentRow.DataBoundItem as Task;
            }
        }

        public DateTime DetailCreateTimeEnd
        {
            get
            {
                return dateTimePickerDetCreateEnd.Value;
            }
            set
            {
                dateTimePickerDetCreateEnd.Value = value;
            }
        }

        public DateTime DetailCreateTimeStart
        {
            get
            {
                return dateTimePickerDetCreateStart.Value;
            }
            set
            {
                dateTimePickerDetCreateStart.Value= value;
            }
        }

        public List<dynamic> DetailsearchView
        {
            get
            {
                return dataGridViewDetail.DataSource as List<dynamic>;
            }
            set
            {
                dataGridViewDetail.DataSource = value;
                dataGridViewDetail.Refresh();
            }
        }

        public string InputSearchWord
        {
            get { return textBoxInputSearchWord.Text; }
            set {}
        }

        public string DetailSearchWord
        {
            get
            {
                return textBoxDetSearchWord.Text;
            }
            set
            {
                textBoxDetSearchWord.Text= value;
            }
        }

        public DateTime DetailUpdateTimeEnd
        {
            get
            {
                return dateTimePickerDetUpdateEnd.Value;
            }
            set
            {
                dateTimePickerDetUpdateEnd.Value=value;
            }
        }

        public DateTime DetailUpdateTimeStart
        {
            get
            {
                return dateTimePickerDetUpdateStart.Value;
            }
            set
            {
                dateTimePickerDetUpdateStart.Value=value;
            }
        }

        public int FilterStatus
        {
            get
            {
                return (comboBoxFilterStatus.SelectedItem as StatusDomain).ID;
            }
            set
            {
                
            }
        }

        public string FilterTime
        {
            get
            {
                return comboBoxFilterTime.SelectedItem.ToString();
            }
            set
            {
                comboBoxFilterTime.SelectedItem = value;
            }
        }

        public void ShowMessage(string message)
        {
            MessageBox.Show(message); ;
        }

        public DateTime SummaryCreateTimeEnd
        {
            get
            {
                return dateTimePickerCreateEnd.Value;
            }
            set
            {
                dateTimePickerCreateEnd.Value= value;
            }
        }

        public DateTime SummaryCreateTimeStart
        {
            get
            {
                return dateTimePickerCreateStart.Value;
            }
            set
            {
                dateTimePickerCreateStart.Value = value;
            }
        }

        public DateTime SummaryReportCreateTimeEnd
        {
            get
            {
                return dateTimePickerRptCreateEnd.Value;
            }
            set
            {
                dateTimePickerRptCreateEnd.Value = value;
            }
        }

        public DateTime SummaryReportCreateTimeStart
        {
            get
            {
                return dateTimePickerRptCreateStart.Value;
            }
            set
            {
                dateTimePickerRptCreateStart.Value=value;
            }
        }

        public DateTime SummaryReportUpdateTimeEnd
        {
            get
            {
                return dateTimePickerRptUpdateEnd.Value;
            }
            set
            {
                dateTimePickerRptUpdateEnd.Value=value;
            }
        }

        public DateTime SummaryReportUpdateTimeStart
        {
            get
            {
                return dateTimePickerRptUpdateStart.Value;
            }
            set
            {
                dateTimePickerRptUpdateStart.Value=value;
            }
        }

        public DateTime SummaryUpdateTimeEnd
        {
            get
            {
                return dateTimePickerUpdateEnd.Value;
            }
            set
            {
                dateTimePickerUpdateEnd.Value=value;
            }
        }

        public DateTime SummaryUpdateTimeStart
        {
            get
            {
                return dateTimePickerUpdateStart.Value;
            }
            set
            {
                dateTimePickerUpdateStart.Value=value;
            }
        }

        public List<dynamic> TaskSearchView
        {
            get
            {
                return dataGridViewSummary.DataSource as List<dynamic>;
            }
            set
            {
                dataGridViewSummary.DataSource = value;
                dataGridViewSummary.Refresh();
            }
        }

      


        public List<ReportDataSummary> ReportSource
        {
            get
            {
                return null;
            }
            set
            {
                reportViewerTracker.LocalReport.DataSources
                    .Add(new ReportDataSource("DataSetSummary", value));
                reportViewerTracker.RefreshReport();
            }
        }

        public string ReportPath
        {
            get
            {
                return reportViewerTracker.LocalReport.ReportPath;
            }
            set
            {
                reportViewerTracker.LocalReport.ReportPath = value;
            }
        }


        public List<StatusDomain> FilterStatusSource
        {
            get
            {
                return comboBoxFilterStatus.DataSource as List<StatusDomain>;
            }
            set
            {
                comboBoxFilterStatus.DataSource = value;
                comboBoxFilterStatus.DisplayMember = "status";
                comboBoxFilterStatus.Refresh();
            }
        }

        public List<string> FilterTimeSource
        {
            get
            {
                return comboBoxFilterTime.DataSource as List<string>;
            }
            set
            {
                comboBoxFilterTime.DataSource = value;
                comboBoxFilterTime.Refresh();
            }
        }

        public BindingList<dynamic> TaskInputView
        {
            get
            {
                return dataGridViewTaskList.DataSource as BindingList<dynamic>;
            }
            set
            {
                this.dataGridViewTaskList.DataSource = value;
                if (value.Count > 0)
                {

                    this.dataGridViewTaskList.Columns["ID"].Width = 30;
                    this.dataGridViewTaskList.Columns["Description"].Width = 120;

                    if (!dataGridViewTaskList.Columns.Contains("Status"))
                    {
                        dataGridViewTaskList.Columns.Add(new DataGridViewComboBoxColumn()
                        {
                            DataSource = FilterStatusSource.Where(s => s.Status != "All").ToList(),
                            DisplayMember = "Status",
                            ValueMember = "ID",
                            DataPropertyName = "StatusId",
                            HeaderText = "Status",
                            Name = "Status",

                        });

                    }

                    dataGridViewTaskList.Columns["CreatedDate"].ReadOnly = true;
                    //int i = dataGridViewTaskList.Columns["Description"].DisplayIndex + 1;

                    if (!dataGridViewTaskList.Columns.Contains("Delete"))
                    {
                        var btnDel = new DataGridViewButtonColumn()
                        {
                            Text = "X",

                            DataPropertyName = "ID",
                            HeaderText = "Del",
                            Name = "Delete",
                            UseColumnTextForButtonValue = true,
                            Width = 30,
                            DefaultCellStyle = new DataGridViewCellStyle() { ForeColor = Color.Red, Alignment = DataGridViewContentAlignment.MiddleCenter }
                        };

                        dataGridViewTaskList.Columns.Add(btnDel);
                    }

                    dataGridViewTaskList.Columns["Note"].Visible = false;

                    dataGridViewTaskList.Columns["CreatedBy"].Visible = false;
                    dataGridViewTaskList.Columns["ModifiedDate"].Visible = false;
                    dataGridViewTaskList.Columns["ModifiedBy"].Visible = false;
                    dataGridViewTaskList.Columns["Task_logLogList"].Visible = false;
                    dataGridViewTaskList.Columns["status_taskStatusDomain"].Visible = false;
                    dataGridViewTaskList.Columns["StatusId"].Visible = false;

                    dataGridViewTaskList.Columns["ID"].DisplayIndex = 0;
                    dataGridViewTaskList.Columns["Description"].DisplayIndex = 1;
                    dataGridViewTaskList.Columns["CreatedDate"].DisplayIndex = dataGridViewTaskList.Columns.Count - 3;
                    dataGridViewTaskList.Columns["Delete"].DisplayIndex = dataGridViewTaskList.Columns.Count - 1;
                    dataGridViewTaskList.Columns["Status"].DisplayIndex = dataGridViewTaskList.Columns.Count - 2;
                    dataGridViewTaskList.Rows[0].Selected = true;
                    dataGridViewTaskList.Refresh();
                    dataGridViewTaskList.Refresh();

                    Files.Text = string.Empty;
                    Files.Refresh();

                }
            }
        }

        public BindingList<Log> LogInputView
        {
           
            set
            {
                if (value != null)
                {
                    dataGridViewTaskDetail.DataSource = value;
                    dataGridViewTaskDetail.Columns["ID"].Visible = true;
                    dataGridViewTaskDetail.Columns["CreatedDate"].Visible = false;
                    dataGridViewTaskDetail.Columns["CreatedBy"].Visible = false;
                    dataGridViewTaskDetail.Columns["ModifiedBy"].Visible = false;
                    dataGridViewTaskDetail.Columns["TaskId"].Visible = false;
                    dataGridViewTaskDetail.Columns["UpdateTime"].Visible = false;
                    dataGridViewTaskDetail.Columns["Note"].Visible = false;
                    dataGridViewTaskDetail.Columns["Task_LogTask"].Visible = false;
                    dataGridViewTaskDetail.Columns["Status_LogStatusDomain"].Visible = false;
                    dataGridViewTaskDetail.Columns["ModifiedDate"].ReadOnly = true;

                    dataGridViewTaskDetail.Columns["ID"].DisplayIndex = 0;
                    dataGridViewTaskDetail.Columns["StatusId"].Visible = false;

                    dataGridViewTaskDetail.Columns["ID"].Width = 30;
                    dataGridViewTaskDetail.Columns["Description"].Width = 218;


                    if (!dataGridViewTaskDetail.Columns.Contains("Status"))
                    {
                        dataGridViewTaskDetail.Columns.Add(new DataGridViewComboBoxColumn()
                        {
                            DataSource = FilterStatusSource.Where(s => s.Status != "All").ToList(),
                            DisplayMember = "Status",
                            ValueMember = "ID",
                            DataPropertyName = "StatusId",
                            HeaderText = "Status",
                            Name = "Status"

                        });

                    }
                    if (!dataGridViewTaskDetail.Columns.Contains("Delete"))
                    {
                        var btnDel = new DataGridViewButtonColumn()
                        {
                            Text = "X",

                            DataPropertyName = "ID",
                            HeaderText = "Del",
                            Name = "Delete",
                            UseColumnTextForButtonValue = true,
                            Width = 33,
                            DefaultCellStyle = new DataGridViewCellStyle() { ForeColor = Color.Red, Padding = new Padding(2, 0, 2, 0), Alignment = DataGridViewContentAlignment.MiddleCenter }
                            // DisplayIndex = dataGridViewTaskDetail.Columns.Count
                        };


                        dataGridViewTaskDetail.Columns.Add(btnDel);
                    }
                    dataGridViewTaskDetail.Columns["Delete"].DisplayIndex = dataGridViewTaskDetail.Columns.Count - 1;
                    dataGridViewTaskDetail.Columns["Status"].DisplayIndex = dataGridViewTaskDetail.Columns.Count - 2;
                    dataGridViewTaskDetail.Columns["ModifiedDate"].DisplayIndex = dataGridViewTaskDetail.Columns.Count - 3;

                }
                else
                {
                    dataGridViewTaskDetail.DataSource = null;
                }

                dataGridViewTaskDetail.Refresh();
            }
        }


        public string FilePath
        {
            get
            {
                return Files.Text;
            }
            set
            {
                Files.Text = value;
                Files.Refresh(); ;
            }
        }

        
        #endregion

       

    }

}
